package com.huiyujinrong.qiangdanbao;

import android.app.Application;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.os.StrictMode;
import android.support.v4.app.FragmentActivity;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.growingio.android.sdk.collection.Configuration;
import com.growingio.android.sdk.collection.GrowingIO;
import com.huiyujinrong.qiangdanbao.network.Api;
import com.huiyujinrong.qiangdanbao.utils.OSUtils;
import com.huiyujinrong.qiangdanbao.utils.PicassoImageLoader;
import com.huiyujinrong.qiangdanbao.utils.RequestInterceptor;
import com.huiyujinrong.qiangdanbao.utils.SharedHelper;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.view.CropImageView;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.beta.Beta;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.Config;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.common.QueuedWork;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Locale;

import happyloan.core.GlobeConfigModule;

public class BorrowHelpApp extends Application {
    private static final String BUGLY_APP_ID = "8ef0a65127";
    private AppComponent appComponent;
    private static BorrowHelpApp app;
    private String version;
    private String IMEI = "";
    private String channel = "develop";

    public static BorrowHelpApp get() {
        return app;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        app = this;
//        initBugly();
        setupDagger();
        Fresco.initialize(this);
        initGrowing();
        MobclickAgent.setScenarioType(this, MobclickAgent.EScenarioType.E_UM_NORMAL); //友盟统计


        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();
        initImagePicker();
        UMShareAPI.get(this);

        //开启debug模式，方便定位错误，具体错误检查方式可以查看http://dev.umeng.com/social/android/quick-integration的报错必看，正式发布，请关闭该模式
        Config.DEBUG = false;
        QueuedWork.isUseThreadPool = false;
    }

    {
        PlatformConfig.setWeixin("wx6ff8c8b65a7e7982", "a916ca4f3b0cf682c4189b634e242f54");
        PlatformConfig.setQQZone("1106229240", "4sCkAs8NmmJiDPcL");
        PlatformConfig.setSinaWeibo("3147281501", "41baf1438ea4d677c0d72b7666873301", "http://qdb.huiyujinrong.com");
//        68cb75a21e675c978346d876e0204781

    }

    private void initImagePicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new PicassoImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setMultiMode(true);
        imagePicker.setSelectLimit(1);
        imagePicker.setCrop(true);        //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true); //是否按矩形区域保存
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(1000);   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);//保存文件的宽度。单位像素
        imagePicker.setOutPutY(800);//保存文件的高度。单位像素

    }

    private void initGrowing() {
        GrowingIO.startWithConfiguration(this, new Configuration().useID().trackAllFragments().setChannel(getChannel()));
    }

    private void setupDagger() {
        appComponent = DaggerAppComponent.builder().globeConfigModule(getModule()).serviceModule(new ServiceModule()).build();
    }

    private GlobeConfigModule getModule() {
        return GlobeConfigModule.builder()
                .setHost(Api.HOST)//请求主机
                .setConnectTimeout(10)//链接超时时间
                .setReadTimeout(10)//读取超时时间
                .setWriteTimeout(20)//写入超时时间
                .setInterceptor(new RequestInterceptor())//设置请求拦截器
                .build();
    }

    /**
     * 更新
     */
    private void initBugly() {
        Beta.autoInit = true;
        Beta.autoCheckUpgrade = true;//true表示初始化时自动检查升级
        Beta.initDelay = 5 * 1000;//设置升级周期为5s
        Beta.largeIconId = R.drawable.icon__login_logo;//设置通知栏大图标，largeIconId为项目中的图片资源；
        Beta.storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);//设置sd卡的Download为更新资源保存目录;

        /**
         * 点击过确认的弹窗在APP下次启动自动检查更新时会再次显示;
         */
        Beta.showInterruptedStrategy = false;

        /**
         * 只允许在MainActivity上显示更新弹窗，其他activity上不显示弹窗;
         * 不设置会默认所有activity都可以显示弹窗;
         */
        Beta.canShowUpgradeActs.add(FragmentActivity.class);
        Beta.autoDownloadOnWifi = true;

        /**
         *  设置自定义升级对话框UI布局
         *  注意：因为要保持接口统一，需要用户在指定控件按照以下方式设置tag，否则会影响您的正常使用：
         *  标题：beta_title，如：android:tag="beta_title"
         *  升级信息：beta_upgrade_info  如： android:tag="beta_upgrade_info"
         *  更新属性：beta_upgrade_feature 如： android:tag="beta_upgrade_feature"
         *  取消按钮：beta_cancel_button 如：android:tag="beta_cancel_button"
         *  确定按钮：beta_confirm_button 如：android:tag="beta_confirm_button"
         *  详见layout/upgrade_dialog.xml
         */
        Beta.upgradeDialogLayoutId = R.layout.upgrade_dialog;

        Bugly.init(this, BUGLY_APP_ID, false);

    }


    /**
     * @return 打包渠道名
     */
    public String getChannel() {
        if (channel.equals("develop")) {
            OSUtils.getPackageChannelFromMetaData(this, "UMENG_CHANNEL");
        }
        return channel;
    }

    public String getPhoneIMEI() {
        if (IMEI == null || IMEI.equals("")) {
            return IMEI = OSUtils.getPhoneIMEI(this);
        } else {
            return IMEI;
        }
    }

    public void setIMEI(String imei) {
        this.IMEI = imei;
    }

    /**
     * @return 当前版本号
     */
    public String getVersion() {
        if (version == null) {
            version = OSUtils.getAPPVersion(this);
        }
        return version;
    }

    public AppComponent getAppComponent() {
        return appComponent;
    }

    public static void showLOG(String val) {
    }

    //user_id
    public static void setUser_id(Context context, String user_id) {
        SharedHelper.put(context, "user_id", user_id);
    }

    public static String getUser_id(Context context) {
        String data = String.valueOf(SharedHelper.get(context, "user_id", ""));
        return data;
    }

    //手机号
    public static void setTel(Context context, String tel) {
        SharedHelper.put(context, "tel", tel);
    }

    public static String getTel(Context context) {
        String data = String.valueOf(SharedHelper.get(context, "tel", ""));
        return data;
    }

    //密码
    public static void setPwd(Context context, String pwd) {
        SharedHelper.put(context, "pwd", pwd);
    }

    public static String getPwd(Context context) {
        String data = String.valueOf(SharedHelper.get(context, "pwd", ""));
        return data;
    }


    public static String getsHA1(Context context) {
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), PackageManager.GET_SIGNATURES);
            byte[] cert = info.signatures[0].toByteArray();
            MessageDigest md = MessageDigest.getInstance("SHA1");
            byte[] publicKey = md.digest(cert);
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < publicKey.length; i++) {
                String appendString = Integer.toHexString(0xFF & publicKey[i])
                        .toUpperCase(Locale.US);
                if (appendString.length() == 1)
                    hexString.append("0");
                hexString.append(appendString);
                hexString.append(":");
            }
            String result = hexString.toString();
            return result.substring(0, result.length() - 1);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
}
